package com.tanhua.server.service;

import cn.hutool.core.collection.CollUtil;
import com.tanhua.dubbo.api.CommentApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.model.db.UserInfo;
import com.tanhua.model.mongo.Comment;
import com.tanhua.model.vo.CommentVo;
import com.tanhua.model.vo.PageResult;
import com.tanhua.server.interceptor.UserHolder;
import org.apache.dubbo.config.annotation.DubboReference;
import org.bson.types.ObjectId;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class CommentsService {

    @DubboReference
    private CommentApi commentApi;

    @DubboReference
    private UserInfoApi userInfoApi;

    //查询动态评论（动态id，互动类型=2）
    public PageResult findComments(String movementId, Integer page, Integer pagesize) {
        Integer commentType = 2 ;// 评论
        //1、调用API，根据动态id，互动类型，分页查询评论数据  List<Comment>
        List<Comment> list =  commentApi.findComments(movementId,commentType,page,pagesize);
        //2、判断List<Comment>是否为空
        if(CollUtil.isEmpty(list)) {
            return new PageResult();
        }
        //获取所有评论列表中的评论人
        List<Long> ids = CollUtil.getFieldValues(list, "userId", Long.class);
        //调用API一次性查询所有评论人信息
        Map<Long, UserInfo> map = userInfoApi.findByIds(ids);
        //3、循环List<Comment>，一个Comment构建一个VO
        List<CommentVo> vos = new ArrayList<>();
        for (Comment comment : list) {
            //获取互动的操作人
            Long userId = comment.getUserId();
            //获取互动操作人的信息
            UserInfo userInfo = map.get(userId);
            CommentVo vo = CommentVo.init(userInfo, comment);//评论发布人的信息，互动对象
            vos.add(vo);
        }
        //4、返回
        return new PageResult(page,pagesize,0l,vos);
    }

    //保存互动评论数据
    public void saveComment(String movementId, String content) {
        Integer commentType = 2;
        //1、创建Comment对象，设置属性值
        Comment comment = new Comment();
        comment.setPublishId(new ObjectId(movementId));
        comment.setCommentType(commentType);
        comment.setContent(content);
        comment.setUserId(UserHolder.getUserId());
        comment.setCreated(System.currentTimeMillis());
        //2、调用API保存 （保存之后，返回评论总数）
        Integer count = commentApi.save(comment);
        System.out.println("评论总数="+count);
    }
}
